﻿
using System.Text.Json;

namespace AhCha.Fortunate.Common
{

    #region Newtonsoft.Json


    /// <summary>
    /// Newtonsoft.Json  雪花id丢失精度解决
    /// </summary>
    public class LongJsonConverter : Newtonsoft.Json.JsonConverter
    {
        public override bool CanRead => false;

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(long) || objectType == typeof(long?);
        }

        public override object? ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object? existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object? value, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else
            {
                writer.WriteValue(value.ToString());
            }
        }
    }


    #endregion



    #region System.Text.Json

    //设置自定义输出配置

    /// <summary>
    /// System.Text.Json  雪花id丢失精度解决
    /// </summary>
    public class SnowflakeIdConverter : System.Text.Json.Serialization.JsonConverter<long>
    {
        public override long Read(ref System.Text.Json.Utf8JsonReader reader, Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
        {
            return long.Parse(reader.GetString()); // 从字符串解析为长整数
        }

        public override void Write(System.Text.Json.Utf8JsonWriter writer, long value, System.Text.Json.JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString()); // 将长整数转换为字符串
        }
    }

    /// <summary>
    /// System.Text.Json  格式化日期
    /// </summary>
    public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
    {

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            // 实现反序列化逻辑（如果需要）
            // 这里可以简单地抛出异常，或者尝试解析字符串为 DateTime
            throw new NotImplementedException();
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            string formattedDate = value.ToString(DateTimeFormatSettings.FormatString, System.Globalization.CultureInfo.InvariantCulture);
            writer.WriteStringValue(formattedDate);
        }
    }
    public static class DateTimeFormatSettings
    {
        public static string FormatString { get; set; }
    }

    #endregion
}
